/*
 * ComerciosAgregarFrame.java
 *
 * Created on 16 de abril de 2008, 12:06 PM
 */
package org.morosidad.porcentajes;

import org.mybeans.Sesion;
import org.mybeans.ContribuyentesBeans;
import org.mybeans.ComerciosBeans;

import java.sql.ResultSet;
import java.sql.PreparedStatement;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import org.sirmupadbapi.beans.Porcentajesmorosidadanual;
import org.sirmupadbapi.controller.PorcentajesmorosidadanualController;
import org.sirmupadbapi.generales.Mensajeria;

/**
 *
 * @author avbravo
 */
public class PorcentajesMorosidadAnualAgregarFrame extends javax.swing.JFrame {

    Sesion sesion;
  Porcentajesmorosidadanual porcentajesmorosidadanual1 = new Porcentajesmorosidadanual();
        PorcentajesmorosidadanualController porcentajesmorosidadanualController1 = new PorcentajesmorosidadanualController();
    /**
     * Creates new form ComerciosAgregarFrame
     */
    public PorcentajesMorosidadAnualAgregarFrame() {
        initComponents();
        /*
         * Fondo
         */
      
        jPanelFondo.setOpaque(false);
        setContentPane(jPanelFondo);
        /*
         * fondo
         */
        sesion = new Sesion();


        java.util.Calendar ca = java.util.Calendar.getInstance();
        java.sql.Date mydate = new java.sql.Date(ca.getTimeInMillis());
        jFormattedTextFieldFechaInicio.setValue(mydate);

        CrearNuevo();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanelFondo = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldIdPorcentaje = new javax.swing.JTextField();
        jButtonNuevo = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jButtonGuardar = new javax.swing.JButton();
        jButtonLimpiar = new javax.swing.JButton();
        jButtonRegresar = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jFormattedTextFieldFechaInicio = new javax.swing.JFormattedTextField();
        jTextFieldPorcentaje = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Agregar Porcentajes de Morosidad Anual");

        jPanelFondo.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Codigo");

        jTextFieldIdPorcentaje.setColumns(35);
        jTextFieldIdPorcentaje.setEditable(false);
        jTextFieldIdPorcentaje.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldIdPorcentajeActionPerformed(evt);
            }
        });

        jButtonNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/new.jpeg"))); // NOI18N
        jButtonNuevo.setToolTipText("Crear nuevo");
        jButtonNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNuevoActionPerformed(evt);
            }
        });

        jLabel2.setText("Porcentaje(%)");

        jLabel3.setText("Fecha Inicio");

        jButtonGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/save.png"))); // NOI18N
        jButtonGuardar.setToolTipText("Guardar");
        jButtonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGuardarActionPerformed(evt);
            }
        });

        jButtonLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/escoba.png"))); // NOI18N
        jButtonLimpiar.setToolTipText("Limpiar");
        jButtonLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonLimpiarActionPerformed(evt);
            }
        });

        jButtonRegresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/regresar.jpeg"))); // NOI18N
        jButtonRegresar.setToolTipText("Regresar");
        jButtonRegresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRegresarActionPerformed(evt);
            }
        });

        jLabel5.setText("Ejemplo:  Para el 20% solo ingrese 20.");

        jFormattedTextFieldFechaInicio.setEditable(false);
        jFormattedTextFieldFechaInicio.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd/MM/yyyy"))));
        jFormattedTextFieldFechaInicio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFormattedTextFieldFechaInicioActionPerformed(evt);
            }
        });

        jTextFieldPorcentaje.setText("10.00");
        jTextFieldPorcentaje.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldPorcentajeActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanelFondoLayout = new javax.swing.GroupLayout(jPanelFondo);
        jPanelFondo.setLayout(jPanelFondoLayout);
        jPanelFondoLayout.setHorizontalGroup(
            jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelFondoLayout.createSequentialGroup()
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanelFondoLayout.createSequentialGroup()
                        .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(0, 0, 0))
                    .addGroup(jPanelFondoLayout.createSequentialGroup()
                        .addComponent(jButtonGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelFondoLayout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(jButtonLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonRegresar, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanelFondoLayout.createSequentialGroup()
                        .addComponent(jTextFieldPorcentaje, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel5))
                    .addComponent(jFormattedTextFieldFechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanelFondoLayout.createSequentialGroup()
                        .addComponent(jTextFieldIdPorcentaje, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonNuevo)))
                .addContainerGap(40, Short.MAX_VALUE))
        );
        jPanelFondoLayout.setVerticalGroup(
            jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelFondoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldIdPorcentaje, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonNuevo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel5)
                        .addComponent(jTextFieldPorcentaje, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jFormattedTextFieldFechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(38, 38, 38)
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonRegresar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(25, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelFondo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelFondo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jTextFieldIdPorcentajeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldIdPorcentajeActionPerformed
}//GEN-LAST:event_jTextFieldIdPorcentajeActionPerformed

private void jButtonRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRegresarActionPerformed

    dispose();
}//GEN-LAST:event_jButtonRegresarActionPerformed

private void jButtonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGuardarActionPerformed


    try {
        String SIdPorcentaje = this.jTextFieldIdPorcentaje.getText();
        if (SIdPorcentaje == null || SIdPorcentaje.equals("")) {
            JOptionPane.showMessageDialog(this, "Presione el boton Crear nuevo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldIdPorcentaje.requestFocus();
            return;
        }
        int IdPorcentajeMorosidadAnual = Integer.parseInt(SIdPorcentaje);
        if (IdPorcentajeMorosidadAnual <= 0) {
            JOptionPane.showMessageDialog(this, "Presione el boton Crear Nuevo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldIdPorcentaje.requestFocus();
            return;
        }

        String SPorcentaje = this.jTextFieldPorcentaje.getText();
        if (SPorcentaje == null || SPorcentaje.equals("")) {
            JOptionPane.showMessageDialog(this, "ingrese el porcentaje", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldPorcentaje.requestFocus();
            return;
        }
        double porcentaje = Double.parseDouble(SPorcentaje);
        if (porcentaje <= 0 || porcentaje > 100) {
            JOptionPane.showMessageDialog(this, "El porcentaje debe ser un valor entre 0.1 y 100", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldIdPorcentaje.requestFocus();
            return;
        }


        String sFecha = jFormattedTextFieldFechaInicio.getText();
        if (sFecha == null || sFecha.equals("")) {
            JOptionPane.showMessageDialog(this, "seleccione la fecha de inicio", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jFormattedTextFieldFechaInicio.requestFocus();
        }
/*
 * pone en inactivo los anteriores
 */
        String sql="activo='no' where idmunicipio='"+sesion.getIdmunicipio()+"' and activo='si'";
      
        if(porcentajesmorosidadanualController1.update(sql)){
           
        }
        


        if (sesion.Conectar() == false) {
            JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        String sqlquery = "select * from porcentajesmorosidadanual  where idmunicipio = ? and activo='si' ";
        PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
        psquery.setString(1, sesion.getIdmunicipio());
        ResultSet rs = psquery.executeQuery();
        rs.next();
        int x = rs.getRow();

        if (x != 0) {
            JOptionPane.showMessageDialog(this, "Existe un porcentaje de morosidad anual activo.No se puede crear otro.", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            sesion.con.close();
            return;
        }
        String sqlupdate = "INSERT into porcentajesmorosidadanual  VALUES(?,?,?,?,?,?,?,?)";
        PreparedStatement prest = sesion.con.prepareStatement(sqlupdate);

        prest.setInt(1, IdPorcentajeMorosidadAnual);
        prest.setDouble(2, porcentaje);

        java.util.Date myFecha = (java.util.Date) jFormattedTextFieldFechaInicio.getValue();
        java.sql.Date date = new java.sql.Date(myFecha.getTime());
        prest.setDate(3, date);
        prest.setDate(4, null);//fechaterminacion
        java.util.Calendar ca = java.util.Calendar.getInstance();
        java.sql.Date mydate = new java.sql.Date(ca.getTimeInMillis());
        prest.setDate(5, mydate);
        prest.setString(6, "si");
        prest.setString(7, sesion.getUsername());//username
        prest.setString(8, sesion.getIdmunicipio());
        int count = prest.executeUpdate();

        sesion.con.close();
        JOptionPane.showMessageDialog(this, "Porcentaje de morosidad guardado exitosamente", "Mensaje", JOptionPane.INFORMATION_MESSAGE);

    } catch (Exception ex) {
        System.out.println("Error" + ex);
        JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }

}//GEN-LAST:event_jButtonGuardarActionPerformed

private void jButtonLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLimpiarActionPerformed

    Limpiar();
}//GEN-LAST:event_jButtonLimpiarActionPerformed

private void jButtonNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNuevoActionPerformed

    CrearNuevo();
}//GEN-LAST:event_jButtonNuevoActionPerformed

private void jFormattedTextFieldFechaInicioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFormattedTextFieldFechaInicioActionPerformed
}//GEN-LAST:event_jFormattedTextFieldFechaInicioActionPerformed

private void jTextFieldPorcentajeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldPorcentajeActionPerformed
}//GEN-LAST:event_jTextFieldPorcentajeActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PorcentajesMorosidadAnualAgregarFrame().setVisible(true);
            }
        });
    }

    private void Limpiar() {
        this.jTextFieldIdPorcentaje.setText("");
        this.jTextFieldPorcentaje.setText("10.0");
        java.util.Calendar ca = java.util.Calendar.getInstance();
        java.sql.Date mydate = new java.sql.Date(ca.getTimeInMillis());
        jFormattedTextFieldFechaInicio.setValue(mydate);
    }

    private void CrearNuevo() {
        try {
            Limpiar();


            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            String sqlquery = "select count(*) as total from porcentajesmorosidadanual where idmunicipio = ? ";
            PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
            psquery.setString(1, sesion.getIdmunicipio());

            ResultSet rs = psquery.executeQuery();
            rs.next();
            int total = 0;
            int x = rs.getRow();
            if (x == 0) {
                total = 0;
            } else {
                total = Integer.parseInt(rs.getString("total"));
            }

            total++;
            jTextFieldIdPorcentaje.setText(String.valueOf(total));


            repaint();

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButtonGuardar;
    private javax.swing.JButton jButtonLimpiar;
    private javax.swing.JButton jButtonNuevo;
    private javax.swing.JButton jButtonRegresar;
    private javax.swing.JFormattedTextField jFormattedTextFieldFechaInicio;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanelFondo;
    private javax.swing.JTextField jTextFieldIdPorcentaje;
    private javax.swing.JTextField jTextFieldPorcentaje;
    // End of variables declaration//GEN-END:variables
}
